package com.mediacloud.app.newsmodule.fragment.navlive;


import android.content.Context;
import android.graphics.Color;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mediacloud.app.assembly.views.CircularImageViewX;
import com.mediacloud.app.cloud.ijkplayers.listener.PlayerListener;
import com.mediacloud.app.cloud.ijkplayersdk.music.MusicPlayer;
import com.mediacloud.app.cloud.ijkplayersdk.obj.MediaMusicItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.service.AudioItem;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 音频直播播放View
 * 不支持后台播放
 * citsin
 * 2019/4/2
 */
public final class AudioLiveView extends FrameLayout {
    private final static String TAG = "AudioLiveView";
    private MusicPlayer musicPlayer;
    private ImageView mPlayView;
    private ImageView mBackgroudView;
    private TextView errorView;
    private CircularImageViewX logoView;

    public AudioLiveView(@NonNull Context context) {
        this(context, null);
    }

    public AudioLiveView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AudioLiveView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mBackgroudView = new ImageView(context);
        mBackgroudView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        this.addView(mBackgroudView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        p.gravity = Gravity.CENTER;
        mPlayView = new ImageView(context);
        int size = (int) (context.getResources().getDisplayMetrics().density * 130);
        logoView = new CircularImageViewX(context);
        LayoutParams p0 = new LayoutParams(size, size);
        p0.gravity = Gravity.CENTER;
        addView(logoView, p0);


        size = (int) (context.getResources().getDisplayMetrics().density * 64);
        mPlayView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        errorView = new TextView(context);
        errorView.setTextColor(Color.WHITE);

        LayoutParams p1 = new LayoutParams(size, size);
        p1.gravity = Gravity.CENTER;
        this.addView(mPlayView, p1);
        this.addView(errorView, p);
        errorView.setVisibility(GONE);
        mPlayView.setImageResource(R.drawable.ic_play_arrow_white_48dp);
        mPlayView.setOnClickListener(playClickListener);


    }

    public void setBackgroundImageUrl(String url) {
        if (TextUtils.isEmpty(url)) return;
        Glide.with(this).load(Uri.parse(url)).into(mBackgroudView);
    }

    private final OnClickListener playClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (musicPlayer == null) return;
            if (musicPlayer.isPlaying()) {
                musicPlayer.pause();
                mPlayView.setImageResource(R.drawable.ic_play_arrow_white_48dp);
            } else {
                musicPlayer.play();
                mPlayView.setImageResource(R.drawable.ic_pause_white_48dp);
            }
        }
    };


    private void updatePlay() {
        if (musicPlayer.isPlaying()) {
            mPlayView.setImageResource(R.drawable.ic_pause_white_48dp);
        } else {
            mPlayView.setImageResource(R.drawable.ic_play_arrow_white_48dp);
        }
    }

    public void showPlayError() {
        mPlayView.setVisibility(GONE);
        errorView.setVisibility(VISIBLE);
        logoView.setVisibility(GONE);
        errorView.setText("亲 ,播放出错啦 暂时无法播放哦^_^");
    }

    private final PlayerListener playerListener = new PlayerListener() {
        @Override
        public void onPrepared(int currentMediaIndex) {
        }

        @Override
        public void oncomplete(int currentMediaIndex) {
            updatePlay();
        }

        @Override
        public void onSeek(int currentMediaIndex, long seekTime, long totalTime) {

        }

        @Override
        public void onSeekComplete(int currentMediaIndex) {
        }

        @Override
        public void onstop(int currentMediaIndex) {
            updatePlay();
        }

        @Override
        public void onpause(int currentMediaIndex) {
            updatePlay();
        }

        @Override
        public void onError(int currentMediaIndex, int arg1, int arg2) {
            showPlayError();
        }

        @Override
        public void onstartBuffer(int currentMediaIndex) {
            Log.v(TAG, "onstartBuffer");
        }

        @Override
        public void onPlayingBufferCache(int currentMediaIndex, int arg0) {
            Log.v(TAG, "onPlayingBufferCache" + arg0);
        }

        @Override
        public void onEndBuffer(int currentMediaIndex) {
            Log.v(TAG, "onEndBuffer");
        }
    };

    /**
     *
     */
    public void stop() {
        if (musicPlayer != null) {
            musicPlayer.stop();
        }
        mPlayView.setImageResource(R.drawable.ic_play_arrow_white_48dp);
    }


    public void pause() {
        if (musicPlayer != null)
            musicPlayer.pause();
        mPlayView.setImageResource(R.drawable.ic_play_arrow_white_48dp);
    }

    public void start() {
        if (musicPlayer!= null)
            musicPlayer.start();
        mPlayView.setImageResource(R.drawable.ic_pause_white_48dp);
    }

    public boolean isPlaying() {
        if (musicPlayer != null) {
            return musicPlayer.isPlaying();
        } else {
            return false;
        }
    }

    /**
     *
     */
    public void release() {
        if (musicPlayer != null)
            musicPlayer.release();
    }


    /**
     * @param item
     */
    public void setData(ArticleItem item) {
        //加载logo图
        Log.v(TAG, "logo:" + item.getLogo());
        RequestOptions options = new RequestOptions().placeholder(R.drawable.audio_play_small_btn_bg);
        Glide.with(this).load(Uri.parse(item.getLogo())).apply(options).into(logoView);
        try {
            JSONObject object = new JSONObject(item.getAudio());
            JSONArray array = object.getJSONArray("ANDROID");
            String cdnEncrypt = object.getString("cdnConfigEncrypt");
            List<MediaMusicItem> items = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                AudioItem audioItem = new AudioItem();
                audioItem.url = obj.getString("url");
                audioItem.cdnEncrypt = cdnEncrypt;
                audioItem.cdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv;
                audioItem.cdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key;
                items.add(audioItem);

            }
            if (musicPlayer != null) {
                musicPlayer.stop();
                musicPlayer.release();
                updatePlay();
            }
            musicPlayer = new MusicPlayer(getContext());
            musicPlayer.setOnPlayerListener(playerListener);
            musicPlayer.addMediaObjs(items);
        } catch (JSONException e) {
            showPlayError();
        }
    }


    public void setData(List<MediaMusicItem> items) {

        if (musicPlayer != null) {
            musicPlayer.stop();
            musicPlayer.release();
            updatePlay();
        }
        musicPlayer = new MusicPlayer(getContext());
        musicPlayer.setOnPlayerListener(playerListener);
        musicPlayer.addMediaObjs(items);
    }


    public void setLogo(String logo) {
        RequestOptions options = new RequestOptions().placeholder(R.drawable.audio_play_small_btn_bg);
        Glide.with(this).load(Uri.parse(logo)).apply(options).into(logoView);
    }


}